/**
 * Created by mingtao on 7/21/16.
 * 此部分为联系人页面的脚本
 */

var $table = $('#table'),
  $remove = $('#remove'),
  $group = $('#group'),
  selections = [];
var table2 = $('#group-table');

function initTable() {
  $table = $('#table');
  $remove = $('#remove');
  $group = $('#group-manage');

  /**
   * 表格真正初始化的部分，包含了options和数据
   */
  $table.bootstrapTable({
    formatLoadingMessage: function () {
      return '正在努力地加载数据中，请稍候……';
    },
    formatRecordsPerPage: function (pageNumber) {
      return '每页显示 ' + pageNumber + ' 条记录';
    },
    formatShowingRows: function (pageFrom, pageTo, totalRows) {
      return '显示第 ' + pageFrom + ' 到第 ' + pageTo + ' 条记录，总共 ' + totalRows + ' 条记录';
    },
    formatSearch: function () {
      return '搜索';
    },
    formatNoMatches: function () {
      return '没有找到匹配的记录';
    },
    formatPaginationSwitch: function () {
      return '隐藏/显示分页';
    },
    formatRefresh: function () {
      return '刷新';
    },
    formatToggle: function () {
      return '切换';
    },
    formatColumns: function () {
      return '列';
    },
    height: getHeight(),
    columns: [
      [
        {
          field: 'state',
          checkbox: true,
          align: 'center',
        },
        {
          field: 'name',
          title: '姓名',
          align: 'center',
          formatter: function (value) {
            return '<a href="javascript: void 0" class="title">' + value + '</a>';
          },
          events: operateEvents
        },
        {
          field: 'tel',
          title: '号码',
          editable: false,
          align: 'center'
        },
        {
          field: 'duty',
          title: '职务',
          editable: false,
          align: 'center'
        },
        {
          field: 'unit',
          title: '单位',
          align: 'center'
        },
        {
          field: 'time',
          title: '添加时间',
          align: 'center'
        },
        {
          field: 'group',
          title: '所属群组',
          align: 'center'
        }
      ]
    ],
    data: [
      {
        name: "张三",
        tel: "13888888888",
        duty: "打杂",
        unit: "后勤",
        time: "2016-07-21 12:23:56",
        group: "扫地"
      },
      {
        name: "张三",
        tel: "13888888888",
        duty: "打杂",
        unit: "后勤",
        time: "2016-07-21 12:23:56",
        group: "扫地"
      },
      {
        name: "张三",
        tel: "13888888888",
        duty: "打杂",
        unit: "后勤",
        time: "2016-07-21 12:23:56",
        group: "扫地"
      },
      {
        name: "张三",
        tel: "13888888888",
        duty: "打杂",
        unit: "后勤",
        time: "2016-07-21 12:23:56",
        group: "扫地"
      },
      {
        name: "张三",
        tel: "13888888888",
        duty: "打杂",
        unit: "后勤",
        time: "2016-07-21 12:23:56",
        group: "扫地"
      },
      {
        name: "张三",
        tel: "13888888888",
        duty: "打杂",
        unit: "后勤",
        time: "2016-07-21 12:23:56",
        group: "扫地"
      },
      {
        name: "张三",
        tel: "13888888888",
        duty: "打杂",
        unit: "后勤",
        time: "2016-07-21 12:23:56",
        group: "扫地"
      },
      {
        name: "张三",
        tel: "13888888888",
        duty: "打杂",
        unit: "后勤",
        time: "2016-07-21 12:23:56",
        group: "扫地"
      },
      {
        name: "张三",
        tel: "13888888888",
        duty: "打杂",
        unit: "后勤",
        time: "2016-07-21 12:23:56",
        group: "扫地"
      },
      {
        name: "张三",
        tel: "13888888888",
        duty: "打杂",
        unit: "后勤",
        time: "2016-07-21 12:23:56",
        group: "扫地"
      },
      {
        name: "张三",
        tel: "13888888888",
        duty: "打杂",
        unit: "后勤",
        time: "2016-07-21 12:23:56",
        group: "扫地"
      },
      {
        name: "张三",
        tel: "13888888888",
        duty: "打杂",
        unit: "后勤",
        time: "2016-07-21 12:23:56",
        group: "扫地"
      }
    ]
  });
  // sometimes footer render error.
  setTimeout(function () {
    $table.bootstrapTable('resetView');
  }, 200);

  $table.on('check.bs.table uncheck.bs.table ' +
    'check-all.bs.table uncheck-all.bs.table', function () {
    $remove.prop('disabled', !$table.bootstrapTable('getSelections').length);

    // save your data, here just save the current page
    selections = getIdSelections();
    // push or splice the selections if you want to save all data selections
  });

  $table.on('expand-row.bs.table', function (e, index, row, $detail) {
    if (index % 2 == 1) {
      $detail.html('Loading from ajax request...');
      $.get('LICENSE', function (res) {
        $detail.html(res.replace(/\n/g, '<br>'));
      });
    }
  });


  /**
   * 绑定事件，弹出模态框
   */
  $remove.click(function () {
    $("#confirm_modal").modal('show');
    //$remove.prop('disabled', true);
  });
  $group.click(function () {
    $("#group_modal").modal('show');
  });

  /**
   * 重新调整大小
   */
  $(window).resize(function () {
    $table.bootstrapTable('resetView', {
      height: getHeight()
    });
  });

  /**
   * 群组管理的表格
   * @type {*|jQuery|HTMLElement}
   */
  $table2 = $('#group-table');
  $table2.bootstrapTable({
    height: '80px',
    columns: [
      [
        {
          field: 'state',
          checkbox: true,
          align: 'center',
        },
        {
          field: 'group_name',
          title: '群组名',
          align: 'center',
          formatter: function (value) {
            return '<a href="javascript: void 0" class="title2">' + value + '</a>';
          },
          events: operateEvents
        },
        {
          field: 'num',
          title: '成员数',
          editable: false,
          align: 'center'
        }
      ]
    ],
    data: [
      {group_name: "办公室", num: 5},
      {group_name: "办公室", num: 5},
      {group_name: "指挥中心", num: 3}
    ]
  });
  /**
   * 绑定点击事件
   */
  $('#add-group').click(function () {
    operateEvents['click .title2']();
  });
  $('#add').click(function () {
    operateEvents['click .title']();
  });
  /**
   * 给table加上AdminLTE的box样式，由于这个类是由插件创建的，所以现在只能等它创建好，我把类加上去
   */
  $('.fixed-table-container').addClass('box box-primary');
}

function getIdSelections() {
  return $.map($table.bootstrapTable('getSelections'), function (row) {
    return row.id
  });
}

var func_confirm = function() {};

/**
 * 这里面是表格超链接点击后的行为
 * @type {{[click .title]: Window.operateEvents.'click .title', [click .title2]: Window.operateEvents.'click .title2'}}
 */
window.operateEvents = {
  'click .title': function (e, value, row, index) {
    $('#complex_modal').modal('show');
  },
  'click .title2': function (e, value, row, index) {
    var html = '\
    <div class="alert alert-info alert-dismissible fade in" role="alert">\
      <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>\
      <div class="row">\
        <div class="col-lg-7 col-md-7 col-sm-7 col-xs-7">\
          <div class="controls">\
            <input type="text" class="form-control">\
          </div>\
        </div>\
        <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">\
          <button type="button" class="btn btn-primary btn-flat">确定</button>\
          <button type="button" class="btn btn-default btn-flat" data-dismiss="alert" aria-label="Close">取消</button>\
        </div>\
      </div>\
    </div>\
    ';
    $('#table2-alert').html(html);
  }
};

function getHeight() {
  return $("#right").height();
}

$(function () {
//注入脚本
  var scripts = [
      '__STATIC__/scripts/vendors/bootstrap-table.js',
    ],
    eachSeries = function (arr, iterator, callback) {
      callback = callback || function () {};
      if (!arr.length) {
        return callback();
      }
      var completed = 0;
      var iterate = function () {
        iterator(arr[completed], function (err) {
          if (err) {
            callback(err);
            callback = function () {};
          }
          else {
            completed += 1;
            if (completed >= arr.length) {
              callback(null);
            }
            else {
              iterate();
            }
          }
        });
      };
      iterate();
    };

    eachSeries(scripts, getScript, initTable);
});

function getScript(url, callback) {
  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.src = url;

  var done = false;
  // Attach handlers for all browsers
  script.onload = script.onreadystatechange = function() {
    if (!done && (!this.readyState ||
      this.readyState == 'loaded' || this.readyState == 'complete')) {
      done = true;
      if (callback)
        callback();

      // Handle memory leak in IE
      script.onload = script.onreadystatechange = null;
    }
  };

  head.appendChild(script);

  // We handle everything using the script element injection
  return undefined;
}
